//
//  LFCacheTool.m
//  AntMarket
//
//  Created by LF on 2017/3/21.
//  Copyright © 2017年 LF. All rights reserved.
//

#import "LFCacheTool.h"
#import "LFNetworkTool.h"
#import "LFBaseViewModel.h"

static NSString *kAllAreaInfoKey = @"kAllAreaInfoKey";
static NSString *kAllAreaTimeKey = @"kAllAreaTimeKey";
static NSString *kAllAreaInfoKey_En = @"kAllAreaInfoKey_En";
static NSString *kAllAreaTimeKey_En = @"kAllAreaTimeKey_En";

@interface LFCacheViewModel : LFBaseViewModel

//**  result */
@property (nonatomic, strong) LFNetworkResult *areaResult;


@end

@implementation LFCacheViewModel

@end

@interface LFCacheTool ()

//**  VM */
@property (nonatomic, strong) LFCacheViewModel *cacheVM;

@end

@implementation LFCacheTool

+ (instancetype) sharedCacheTool
{
    static LFCacheTool *sharedTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedTool = [[LFCacheTool alloc] init];
    });
    
    return sharedTool;
}

- (LFCacheViewModel *)cacheVM
{
    if (!_cacheVM) {
        _cacheVM = [[LFCacheViewModel alloc] init];
    }
    return _cacheVM;
}

#pragma mark - 用户
+ (void) cacheUserInfo:(NSDictionary *)dic
{
    [self lf_cacheObject:dic forKey:USER_ACCOUNT_KEY];
}

+ (NSDictionary *)getUserInfo
{
    if ([self lf_getCacheObjectFromKey:USER_ACCOUNT_KEY]) {
        return [self lf_getCacheObjectFromKey:USER_ACCOUNT_KEY];
    } else {
        return nil;
    }
}


+ (void)cacheUserLocation:(NSString *)city {
    [self lf_cacheObject:city forKey:USER_LOCATION];
}

+ (NSString *)location {
    
    if ([self lf_getCacheObjectFromKey:USER_LOCATION]) {
        return [self lf_getCacheObjectFromKey:USER_LOCATION];
    } else {
        return nil;
    }
}


#pragma mark - 广告
+ (void) cacheADInfo:(NSMutableDictionary *)dic
{
    [self lf_cacheObject:dic forKey:HOME_AD_KEY];
    
    NSArray *adNames = dic[@"ad_content"];
    NSDictionary *imgDic = adNames[0];
    NSString *imgName = [imgDic objectForKey:@"img"];
    // TODO 后台调整, 测好之后删除return
//    return;
    NSURL *imageUrl = [NSURL URLWithString: [imgName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    // SDWebImageAvoidAutoSetImage 下载完不给imageView赋值
    [[[SDWebImageManager sharedManager] imageDownloader] downloadImageWithURL:imageUrl options:SDWebImageDownloaderLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (!error) {
            // 加入到单例里面
            [dic setObject:imgName forKey:@"ADIMAGE"];
            
            NSLog(@"图片下载完成");
            
            [self lf_cacheObject:dic forKey:HOME_AD_KEY];
            
            //[[NSNotificationCenter defaultCenter] postNotificationName:kShowADViewInHomeVCNoti object:nil];
            
        } else {
            NSLog(@"%@",error);
        }
    }];
}

+ (NSMutableDictionary *) getADInfo
{
    if ([self lf_getCacheObjectFromKey:HOME_AD_KEY]) {
        return [self lf_getCacheObjectFromKey:HOME_AD_KEY];
    } else {
        return nil;
    }
}

+ (void) removeADInfo
{
    [self removeObjectForKey:HOME_AD_KEY];
}


#pragma mark - 保存信息
+ (void) lf_cacheObject:(id)object forKey:(NSString *)key
{
    NSUserDefaults * defults = [NSUserDefaults standardUserDefaults];
   // NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.Com.Muxi.Need"];
    [defults setObject:object forKey:key];
    [defults synchronize];

}

+ (id) lf_getCacheObjectFromKey:(NSString *)key
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:key]) {
        return [[NSUserDefaults standardUserDefaults] objectForKey:key];
    } else {
        return nil;
    }
}

+ (void) removeObjectForKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

#pragma mark - 本地用过的标签
+ (void) cacheTagText:(NSString *) tagText {
    
    NSArray *localTagTextArr = [self lf_getLocalTags];
    
    if (localTagTextArr == nil) {
        localTagTextArr = [NSArray array];
    }
    
    // 本地没有这一条
    if ([localTagTextArr containsObject:tagText] == NO) {
        NSMutableArray *arr = [localTagTextArr mutableCopy];
        [arr insertObject:tagText atIndex:0];
        if (arr.count > 3) {
            [arr removeLastObject];
        }
        NSString * localTagText = [arr componentsJoinedByString:@"|"];
        [self lf_cacheObject:localTagText forKey:TagTextKey];
    }
}
+ (NSArray *) lf_getLocalTags {
    NSString *localText = [self lf_getCacheObjectFromKey:TagTextKey];
    return [localText componentsSeparatedByString:@"|"];
}

#pragma mark - 清理缓存
+ (void) clearCaches:(void(^)())success
{
    // 删除SDWebImage缓存
    [[SDImageCache sharedImageCache] clearMemory];
    
    // 清除本地的视频
    [self ClearMovieFromDoucmentsThroughly:NO];
    
    // 删除地理信息缓存
    [self removeObjectForKey:kAllAreaInfoKey];
    [self removeObjectForKey:kAllAreaTimeKey];
    
    // 清理广告信息
    [self removeADInfo];

    if (success) {
        success();
    }
}

+ (CGFloat) getCacheSize
{
    NSInteger cachesize = [[SDImageCache sharedImageCache] getSize];
    CGFloat cache = cachesize / 1024.0 / 1024.0;
    
    return cache;
}


#pragma mark - 清除documents中的视频文件
+(void)ClearMovieFromDoucmentsThroughly:(BOOL)throughtly{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 删除转化的视频
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
        NSEnumerator *e = [contents objectEnumerator];
        NSString *filename;
        while ((filename = [e nextObject])) {
            NSLog(@"%@",filename);
            if ([filename isEqualToString:@"tmp.PNG"]) {
                NSLog(@"删除%@",filename);
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
                continue;
            }
            if (throughtly && ([[[filename pathExtension] lowercaseString] isEqualToString:@"caf"]||
                               [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]
                               )) {
                NSLog(@"删除%@",filename);
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
            }
            if ([[[filename pathExtension] lowercaseString] isEqualToString:@"mp4"]||
//                [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"png"]||
//                [[[filename pathExtension] lowercaseString] isEqualToString:@"caf"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"mp3"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"m4a"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"pcm"]) {
                NSLog(@"删除%@",filename);
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
            }

        }
    }
    
    
    // 删除HXPhoto里的
    {
        NSString *documentsDirectory = NSTemporaryDirectory();
        NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
        NSEnumerator *e = [contents objectEnumerator];
        NSString *filename;
        while ((filename = [e nextObject])) {
            NSLog(@"%@",filename);
            if ([filename isEqualToString:@"tmp.PNG"]) {
                NSLog(@"删除%@",filename);
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
                continue;
            }
            if (throughtly && ([[[filename pathExtension] lowercaseString] isEqualToString:@"caf"]||
                               [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]
                               )) {
                NSLog(@"删除%@",filename);
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
            }
            if ([[[filename pathExtension] lowercaseString] isEqualToString:@"mp4"]||
                //                [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"png"]||
                //                [[[filename pathExtension] lowercaseString] isEqualToString:@"caf"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"mp3"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"m4a"]||
                [[[filename pathExtension] lowercaseString] isEqualToString:@"pcm"]) {
                NSLog(@"删除%@",filename);
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
            }        }
        //    return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), [NSString stringWithFormat:@"hx%@.mov",[self videoOutFutFileName]]]];
    }
}


@end
